import 'dart:async';
import 'dart:developer';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/navigation/navigation_logic.dart';
import 'package:ball_lion/module/match/event_data_entity.dart';
import 'package:ball_lion/service/config_service.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/server/ws/ws_manager.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/sound_utils.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/match/match_page.dart';
import 'package:vibration/vibration.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class GetNotifyConfig {
  static bool isInMatchList() {
    if (Get.currentRoute == "/navigation") {
      final c = Get.find<NavigationLogic>();
      if (c.pageList.indexWhere((element) => element is MatchPage) ==
          c.pageController.page) {
        return true;
      }
    }
    return false;
  }

  static List<String> routesIgnore = [
    Routes.viewpoint,
    Routes.userPage,
    Routes.aiPay,
    Routes.subsPay,
    Routes.aiAssess,
    Routes.aiBounce,
    Routes.aiCombo,
    Routes.aiFaith,
    Routes.aiLm,
    Routes.aiTrend,
    Routes.aiPre,
    Routes.aiDetail,
    Routes.myRecharge,
    Routes.homeVideoNews,
    Routes.vipCenter,
    Routes.login,
    Routes.secretList,
    Routes.secretPay,
    Routes.livePush,
    Routes.liveStatistics,
    Routes.liveNormal
  ];

  static isBasketbool(WsEventEntity event) {
    final t = event.eventType ?? -1;
    return t ~/ 100 == 81;
  }

  static isSoccer(WsEventEntity event) {
    final t = event.eventType ?? 0;
    return t ~/ 100 == 82;
  }

  static bool doNotify(WsEventEntity event) {
    try {
      final entity = event.data;
      if (entity == null) {
        return false;
      }
      if (routesIgnore.contains(Get.currentRoute) ||
          Get.mediaQuery.orientation == Orientation.landscape) return false;
      if (Get.currentRoute == Routes.navigation && Get.previousRoute != '/') {
        if (routesIgnore.contains(Get.find<NavigationLogic>().currentRoute))
          return false;
      }

      final config = Get.find<ConfigService>();
      if (!config.tipEnable) {
        return false;
      }

      switch (event.eventType) {
        case 8101:
          //篮球进球
          //是否只提醒关注的
          if (config.lqConfig.lqAlert1 == 0 &&
              !User.basketballFocuses.isFocus(entity.matchQxbId ?? -1)) {
            return false;
          }
          //是否只在比赛列表中提醒
          if (config.lqConfig.lqAlert3 == 0 && !isInMatchList()) {
            return false;
          }
          //是否需要弹窗提示
          if (!config.lqConfig.lqAlert2.contains(0)) {
            return false;
          }
          //播放声音
          if (config.lqConfig.lqAlert2.contains(1)) {
            SoundUtils.playBasketGoal();
          }
          //震动
          if (config.lqConfig.lqAlert2.contains(2)) {
            Vibration.vibrate();
          }
          return true;
        case 8201:
          //足球进球
          //是否只提醒关注的
          if (config.zqConfig.zqAlert1 == 0 &&
              !User.isFollow(entity.matchQxbId ?? -1)) {
            return false;
          }
          //是否只在比赛列表中提醒
          if (config.zqConfig.zqAlert6 == 0 && !isInMatchList()) {
            return false;
          }
          //是否需要弹窗提示
          if (!config.zqConfig.zqAlert2.contains(0)) {
            return false;
          }
          //播放声音
          if (config.zqConfig.zqAlert2.contains(1)) {
            SoundUtils.playSoccerGoal(entity.highLight == 0);
          }
          //震动
          if (config.zqConfig.zqAlert2.contains(2)) {
            Vibration.vibrate();
          }
          return true;
        case 8202:
          //足球红牌
          //是否只提醒关注的
          if (config.zqConfig.zqAlert1 == 0 &&
              !User.isFollow(entity.matchQxbId ?? -1)) {
            return false;
          }
          //是否只在比赛列表中提醒
          if (config.zqConfig.zqAlert6 == 0 && !isInMatchList()) {
            return false;
          }
          //是否需要提示
          if (!config.zqConfig.zqAlert5.contains(0)) {
            return false;
          }
          //播放声音
          if (config.zqConfig.zqAlert5.contains(1)) {
            SoundUtils.playRedCard();
          }
          //震动
          if (config.zqConfig.zqAlert5.contains(2)) {
            Vibration.vibrate();
          }
          return true;
      }
    } catch (err) {
      return false;
    }
    return true;
  }

  static const evIcons = {
    8101: "match_event_lq.png",
    8201: "match_event_zq.png",
    8202: "match_event_zq_red.png"
  };

  static const evRorate = {8101: true, 8201: true, 8202: false};
}

class MatchTipFloatWidget extends StatefulWidget {
  const MatchTipFloatWidget({super.key});

  @override
  State<MatchTipFloatWidget> createState() => _MatchTipFloatWidgetState();
}

class _MatchTipFloatWidgetState extends State<MatchTipFloatWidget> {
  late Timer t;

  int count = 0;
  StreamSubscription? _sub;

  bool showing = false;
  bool drag = false;
  List<WsEvent> events = [];
  WsEventEntity? event;
  late final s = Get.find<ConfigService>();
  bool showSetting = !SpUtils.notifySetted;

  showEvent(WsEventEntity event) {
    if (GetNotifyConfig.isBasketbool(event)) {
    } else if (GetNotifyConfig.isSoccer(event)) {
    } else {
      return;
    }

    showSetting = !SpUtils.notifySetted;
    this.event = event;
    showing = true;
    update();
    final s = (event.holdTime ?? 0) == 0 ? 5 : event.holdTime!;
    Future.delayed(Duration(seconds: s)).then((value) => dismiss(false));
  }

  next() {
    if (event != null) {
      return;
    }
    if (events.isEmpty) {
      return;
    }
    try {
      final e = events.removeAt(0);
      final evEntity = WsEventEntity.fromJson(e);
      if (GetNotifyConfig.doNotify(evEntity)) {
        showEvent(evEntity);
      } else {
        next();
      }
    } catch (err) {
      next();
    }
  }

  dismiss(bool type) {
    if (event == null) {
      return;
    }
    showing = false;
    drag = type;
    update();
    Future.delayed(300.ms).then((value) {
      event = null;
      update();
      next();
    });
  }

  @override
  void initState() {
    super.initState();

    _sub = WebSocketManager.messageStream.listen((WsEvent event) {
      events.add(event);
      next();
    });
  }

  @override
  void dispose() {
    t.cancel();
    _sub?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final padding = MediaQuery.of(context).padding;
    return event != null
        ? Positioned(
            bottom: padding.bottom + 56,
            left: 0,
            right: 0,
            // height: 100,
            child: Dismissible(
                key: Key("match_tip${DateTime.now().microsecondsSinceEpoch}"),
                onDismissed: (miss) => dismiss(true),
                child: _content()))
        : Container();
  }

  Widget _content() {
    List<Color> gradientColors = [
      const Color(0xFFFF9B70),
      const Color(0xFFF45F5F)
    ];
    if (event?.isSoccer ?? false) {
      gradientColors = [const Color(0xFF3F88F5), const Color(0xFF699FFF)];
    }
    final content = Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(
              colors: gradientColors,
              begin: Alignment.centerLeft,
              end: Alignment.centerRight),
          borderRadius: BorderRadius.circular(8)),
      margin: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
      // padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Stack(
        alignment: Alignment.topCenter,
        children: [
          Positioned(
              child: Image.asset(
            Utils.getImgPath(event?.isSoccer == true
                ? 'inapp_tip_zq.png'
                : 'inapp_tip_lq.png'),
            width: 88,
            height: 58,
          )),
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
            child: Column(
              children: [_infoContent(), if (showSetting) _settingView()],
            ),
          ),
        ],
      ),
    );
    return showing
        ? content
            .animate(key: ValueKey("s ${event?.data?.matchQxbId}"))
            .move(
                begin: const Offset(200, 0), end: Offset.zero, duration: 200.ms)
            .fadeIn(delay: 100.ms, duration: 100.ms, begin: 0)
        : drag
            ? Container()
            : content
                .animate(key: ValueKey("e ${event?.data?.matchQxbId}"))
                .move(
                    begin: Offset.zero,
                    end: const Offset(200, 0),
                    duration: 200.ms)
                .fadeOut(delay: 100.ms, duration: 100.ms, begin: 1);
  }

  Widget _settingView() {
    final e = event;
    if (e == null) {
      return Container();
    }
    int f = 0;
    if (GetNotifyConfig.isSoccer(e)) {
      f = s.zqConfig.zqAlert1;
      log("${s.zqConfig.zqAlert1}");
    } else {
      f = s.lqConfig.lqAlert1;
      log("${s.lqConfig.lqAlert1}");
    }

    return Container(
      padding: const EdgeInsets.only(top: 14),
      child: DefaultTextStyle(
        style: const TextStyle(color: Colors.white, fontSize: 12),
        child: Row(
          children: [
            QsText("提醒范围"),
            const SizedBox(
              width: 8,
            ),
            _roundBtn("关注", f == 0).tap(() {
              if (GetNotifyConfig.isSoccer(e)) {
                s.zqConfig.zqAlert1 = 0;
                s.update(ConfigType.zqAlert1, 0);
              } else {
                s.lqConfig.lqAlert1 = 0;
                s.update(ConfigType.lqAlert1, 0);
              }
              update();
              SpUtils.notifySetted = true;
            }),
            const SizedBox(
              width: 5,
            ),
            _roundBtn("全部", f == 1).tap(() {
              if (GetNotifyConfig.isSoccer(e)) {
                s.zqConfig.zqAlert1 = 1;
                s.update(ConfigType.zqAlert1, 1);
              } else {
                s.lqConfig.lqAlert1 = 1;
                s.update(ConfigType.lqAlert1, 1);
              }
              update();
              SpUtils.notifySetted = true;
            }),
            const Spacer(),
            _iconBtn("设置", Utils.getImgPath("match_config.png")).tap(() {
              if (GetNotifyConfig.isSoccer(e)) {
                Get.toNamed(Routes.zqConfig);
              } else {
                Get.toNamed(Routes.lqConfig);
              }
              SpUtils.notifySetted = true;
            })
          ],
        ),
      ),
    );
  }

  Widget _iconBtn(String title, String icon) {
    return Row(
      children: [
        Image.asset(icon, width: 16, height: 16, color: Colours.white)
            .marginOnly(right: 5),
        QsText(title)
      ],
    );
  }

  Widget _roundBtn(String title, bool selected) {
    return Container(
      // padding: EdgeInsets.symmetric(horizontal: 8),
      decoration: BoxDecoration(
          border: selected ? Border.all(color: Colors.white, width: 0.5) : null,
          borderRadius: BorderRadius.circular(10),
          color: const Color(0x1A000000)),
      alignment: Alignment.center,
      width: 32,
      height: 16,
      child: Center(
        child: QsText(
          title,
          fontSize: 10,
          needCenter: true,
        ),
      ),
    );
  }

  Widget _infoContent() {
    EventDataEntity? entity;
    try {
      entity = event?.data;
    } catch (err) {}

    final image = GetNotifyConfig.evIcons[event?.eventType ?? 0] ??
        "match_event_soccer.png";
    final rotate = GetNotifyConfig.evRorate[event?.eventType ?? 0] ?? false;
    Animate icon = Image.asset(Utils.getImgPath(image), width: 44, height: 44)
        .animate(key: ValueKey("a ${event?.data?.matchQxbId}"));
    if (rotate) {
      icon = icon.rotate(duration: 2000.ms, begin: math.pi, end: 0);
    }
    icon = icon.move(
        duration: 2000.ms, begin: const Offset(-10, 0), end: Offset.zero);
    final topEmpty = (entity?.topTeamName ?? "").isEmpty &&
        (entity?.topTeamScore ?? '').isEmpty;
    final bottomEmpty = (entity?.footTeamName ?? '').isEmpty &&
        (entity?.footTeamScore ?? '').isEmpty;
    final midSpace = !topEmpty && !bottomEmpty;
    return DefaultTextStyle(
      style: const TextStyle(color: Colors.white),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Column(
              children: [
                if (!topEmpty)
                  _teamInfo(
                      entity?.topTeamName ?? "", entity?.topTeamScore ?? '',
                      alert: entity?.highLight == 0),
                if (midSpace) const SizedBox(height: 4),
                if (!bottomEmpty)
                  _teamInfo(
                      entity?.footTeamName ?? '', entity?.footTeamScore ?? '',
                      alert: entity?.highLight == 1)
              ],
            ),
          ),
          // Spacer(),
          Container(
            width: 0.5,
            color: Colors.white.withOpacity(0.50),
            height: 44,
            margin: const EdgeInsets.symmetric(horizontal: 16),
          ),
          SizedBox(
              width: 50,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  QsText(entity?.firstTag ?? '', fontSize: 15),
                  const SizedBox(height: 4),
                  QsText(entity?.secTag ?? '', fontSize: 15)
                ],
              )),
        ],
      ),
    ).tap(() {
      final id = event?.data?.matchQxbId;
      final e = event;
      if (id == null || e == null) {
        return;
      }
      if (GetNotifyConfig.isBasketbool(e)) {
        if (Get.currentRoute == Routes.lqMatchDetail) {
          return;
        }
        Get.toNamed(Routes.lqMatchDetail, arguments: id);
        dismiss(false);
      } else if (GetNotifyConfig.isSoccer(e)) {
        if (Get.currentRoute == Routes.zqMatchDetail) {
          return;
        }
        Get.toNamed(Routes.zqMatchDetail, arguments: id);
        dismiss(false);
      }
    });
  }

  Widget _teamInfo(String team, String scoreValue, {bool alert = false}) {
    return DefaultTextStyle(
        style: const TextStyle(
            fontSize: 15, color: Colors.white, fontWeight: FontWeight.w500),
        child: Row(
          children: [
            Expanded(
                child: QsText(
              team,
              maxLines: 1,
              textAlign: TextAlign.left,
            )),
            QsText(scoreValue, maxLines: 1)
          ],
        ));
  }
}
